import { useState, useEffect, useRef } from 'react'
import useMap from '../../hooks/useMap';
import { Overlay } from 'ol';
import _ from 'lodash';

const handleValue = (feature, field) => {
    if (_.isString(field)) {
        return feature?.get(field);
    }
    for (let i = 0; i < field.length; i++) {
        const key = field[i];
        if (feature?.get(key)) {
            return feature?.get(key);
        }
    }
}

export default function MapPointerMove(props) {
    const { field } = props;
    const map = useMap();
    const [title, setTiltle] = useState();
    const popupRef = useRef();
    const overlayRef = useRef();
    // const div = document.createElement("div");
    // popupRef.current?.appendChild(div);
    useEffect(() => {
        if (map) {
            const handler = evt => {
                let popup = overlayRef.current
                if (!overlayRef.current) {
                    popup = overlayRef.current = new Overlay({
                        element: popupRef.current.childNodes[0],
                    });
                    map.addOverlay(popup);
                }
                const features = map.getFeaturesAtPixel(evt.pixel);
                // console.log('features',features)
                const feature = features?.find(feature => {
                    return handleValue(feature, field)
                });
                const coordinate = feature?.getGeometry()?.getCoordinates();
                if (coordinate) {
                    popup.setPosition(coordinate);
                } else {
                    popup.setPosition(undefined);
                }
                const tooltip = handleValue(feature, field);
                if (tooltip) {
                    setTiltle(tooltip);
                } else {
                    popup.setPosition(undefined);
                }
            }
            map.on('pointermove', handler);
            return () => {
                map.un('pointermove', handler);
                overlayRef.current && map.removeOverlay(overlayRef.current);
            }
        }
    }, [map, field])
    return <div ref={popupRef} style={{
        position: "absolute",
        left: -10000
    }}>
        <div style={{
            // position: 'absolute',
            // left: -10000,
            // top: `${position.y - 50}px`,
            display: 'inline-block',
            whiteSpace: 'nowrap',
            borderRadius: 10,/* 设置圆角半径 */
            backgroundColor: 'black', /* 设置背景色为黑色 */
            padding: 10, /* 可选：添加内边距以增加可读性 */
            color: 'white',
        }}>{title}</div>
    </div>;
}